// 假装是个接口
function fetch() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            let random = Math.random();
            console.log("7777 ---- file: index.js:6 ---- random---->", random)
            if (random > 0.5) {
                reject('error')
            } else {
                resolve({
                    code: 200,
                    data: {
                        name: '张三'
                    }
                })
            }

        }, 1000)
    })
}

function m1() {
    return fetch();
}

function m2() {
    return m1();
}

function main() {
    global.fetch = fetch;
    let r = m2();
    console.log('r--->', r);
}

function run(func) {
    let cache = []; // 存放可能多次调取接口的返回值
    let i = 0;
    let _originalFetch = global.fetch; // 在走之前拿到之前的 fetch
    console.log("7777 ---- file: index.js:32 ---- _originalFetch---->", _originalFetch)

    global.fetch = (...args) => {
        if (cache[i]) {
            // 如果是调取接口成功了
            if (cache[i].status === 'fulilled') {
                return cache[i].data;
            }
            else if (cache[i].status === 'rejected') {
                throw cache[i].err;
            }
            return cache[i];
        }
        const ruesult = {
            status: 'pending',
            data: null,
            err: null
        };
        cache[i++] = ruesult;

        // 发送请求
        let prom = _originalFetch(...args).then(
            (resp) => {
                console.log("7777 ---- file: index.js:53 ---- resp---->", resp)
                ruesult.status = 'fulilled';
                ruesult.data = resp;
            },
            err => {
                ruesult.status = 'rejected';
                ruesult.err = err;
            }
        )

        // 报错
        throw prom;
    };

    try {
        func();
    } catch (err) {
        console.log("7777 ---- file: index.js:76 ---- err---->", err)
        // 什么时候重新执行 func
        if (err instanceof Promise) {
            const reRun = () => {
                i = 0;
                func();
            }
            err.then(reRun, reRun)
        }
    }
}

run(main);